package com.dly.blog.handle;

import com.dly.blog.exception.AuthExceptionEnum;
import com.dly.blog.exception.GlobalException;
import com.dly.blog.msg.R;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;

/**
 * 全局异常拦截
 * @Author: DaiLiYu
 * @Date: 2023/7/11 9:18
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 解决 GlobalException 消费权限异常问题
     * @param e
     * @throws AccessDeniedException
     */
    @ExceptionHandler(AccessDeniedException.class)
    public void accessDeniedException(AccessDeniedException e) throws AccessDeniedException {
        throw e;
    }

    /**
     * 拦截所有的异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<R<Void>> errorHandler(Exception e, HttpServletRequest request){
        String requestURI = request.getRequestURI();
        log.error("请求地址：{}，系统异常 类型：{} 信息：{}", e.getClass(), requestURI,e.getMessage());
        e.printStackTrace();
        if(e instanceof AsyncRequestTimeoutException){
            return null;
        }
        if(e instanceof GlobalException exception){
            return ResponseEntity.ok(R.error(exception));
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()));
    }

}
